package baiyuanwei.example.calendar.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.HashMap;

import baiyuanwei.example.calendar.CalendarUtil;

/**
 * Created by baiyuanwei on 16/5/3.
 */
public class MonthDaysView extends View {

    //正常文字的颜色
    private final int DEFAULT_NORMAL_TEXT_COLOR = Color.BLACK;

    //特殊文字的颜色
    private final int DEFAULT_SPECIAL_DAYS_COLOR = Color.BLUE;

    //被点击的那一天的颜色
    private final int DEFAULT_CLICK_DAY_COLOR = Color.parseColor("#FF05E426");

    //默认间隔(圆)
    private final int DEFAULT_SPACE_DISTANCE = 3;

    //默认间隔(字)
    private final int DEFAULT_SPACE_TEXT_DISTANCE = 1;

    private final String DEFAULT_SPECIAL_FLAG_TEXT = "约";

    //默认字体的大小(还要乘以密度)
    private final int DEFAULT_TEXT_SIZE = 12;

    //画笔的宽度
    private final int DEFAULT_PAINT_WIDTH = 1;

    //默认宽高(还要乘以密度)
    private final int DEFAULT_WIDTH = 300;
    private final int DEFAULT_HEIGHT = 200;

    //当天的颜色
    private int nowDayColor = DEFAULT_CLICK_DAY_COLOR;

    //屏幕的密度
    private float density;

    //此view的宽高
    private int width;
    private int height;

    //行数
    private int rowCount;

    //行高
    private int rowHeight;

    //列宽
    private int columnWidth;

    //默认字体大小
    private int paintTextSize;

    //画笔
    private TextPaint textPaint;

    private Paint paint;

    private HashMap<String, Integer> weekNumHash = new HashMap<>();

    //当前的日期
    private String currentDate = "2016-02-01";

    private int nowYear;
    private int nowMonth;
    private int nowDay;

    //这个月的第一天是星期几
    private String firstDayWeek = "";

    //点击此view的初始位置
    private float downX;
    private float downY;

    //当前的月份有多少天
    private int currentMonthDayCount;

    //特殊的days
    private ArrayList<Integer> specialDays = new ArrayList<>();

    //当前的位置
    private int currentRowNum = 2;
    private int currentColumnNum = 1;


    //被选中的日期
    private String selectDate = "";

    /**
     * 日期的点击事件接口
     */
    public interface OnClickDayListener {
        void onClickDay(String date);
    }

    private OnClickDayListener onClickDayListener;

    public void setOnClickDayListener(OnClickDayListener listener) {
        onClickDayListener = listener;
    }


    public MonthDaysView(Context context) {
        this(context, null);
    }

    public MonthDaysView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MonthDaysView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {

        weekNumHash.put("周日", 1);
        weekNumHash.put("周一", 2);
        weekNumHash.put("周二", 3);
        weekNumHash.put("周三", 4);
        weekNumHash.put("周四", 5);
        weekNumHash.put("周五", 6);
        weekNumHash.put("周六", 7);


        specialDays.add(23);
        specialDays.add(26);
        specialDays.add(3);
        specialDays.add(12);
        specialDays.add(7);
        specialDays.add(10);
        specialDays.add(20);

        nowYear = CalendarUtil.getNowYear();
        nowMonth = CalendarUtil.getNowMonth();
        nowDay = CalendarUtil.getNowDay();
        currentDate = nowYear + "-" + nowMonth + "-01";


        firstDayWeek = CalendarUtil.getDayOfWeekByDate(currentDate);
        currentMonthDayCount = CalendarUtil.getDaysByYearMonth(2016, 5);

        //获取屏幕密度
        density = getContext().getResources().getDisplayMetrics().density;

        //默认字体大小
        paintTextSize = (int) (DEFAULT_TEXT_SIZE * density);


        //画笔的默认配置
        textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setStrokeWidth(DEFAULT_PAINT_WIDTH);
        textPaint.setTextSize(paintTextSize);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(DEFAULT_NORMAL_TEXT_COLOR);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStrokeWidth(DEFAULT_PAINT_WIDTH);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension((int) (DEFAULT_WIDTH * density), (int) (DEFAULT_HEIGHT * density));
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension((int) (DEFAULT_WIDTH * density), heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize, (int) (DEFAULT_HEIGHT * density));
        } else {
            setMeasuredDimension(widthSpecSize, heightSpecSize);
        }
    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        width = getWidth();
        height = getHeight();

        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {


        drawClickDay(canvas);

//        drawNowDay(canvas);
        drawMonthDays(canvas);



    }

    /**
     * 画日历
     *
     * @param canvas
     */
    private void drawMonthDays(Canvas canvas) {
        canvas.save();

        int dx = (width - 7 * paintTextSize) / (7 * 2) + paintTextSize / 2;

        int num = weekNumHash.get(firstDayWeek);
        int startX = (2 * num - 1) * dx;

        //行数
        rowCount = currentMonthDayCount / 7 + 1;

        //行高
        rowHeight = height / rowCount;

        //列宽
        columnWidth = 2 * dx;

        int startY = rowHeight / 2 + paintTextSize / 2;
        int dy = rowHeight;

        for (int i = 0; i < currentMonthDayCount; i++) {
            String text = "";
            if (i < 9) {
                text = "0" + (i + 1);
            } else {
                text = "" + (i + 1);
            }
            if (isSpecialDay(i + 1)) {
                textPaint.setColor(DEFAULT_SPECIAL_DAYS_COLOR);
                paint.setColor(DEFAULT_SPECIAL_DAYS_COLOR);
                paint.setStyle(Paint.Style.STROKE);
                canvas.drawCircle(startX, startY - paintTextSize / 2, rowHeight / 2 - DEFAULT_SPACE_DISTANCE * density, paint);
                canvas.drawText(text, startX, startY - paintTextSize / 2 - (DEFAULT_SPACE_TEXT_DISTANCE * density), textPaint);
                canvas.drawText(DEFAULT_SPECIAL_FLAG_TEXT, startX, startY + paintTextSize / 2 + (DEFAULT_SPACE_TEXT_DISTANCE * density), textPaint);
            } else {
                textPaint.setColor(DEFAULT_NORMAL_TEXT_COLOR);
                canvas.drawText(text, startX, startY, textPaint);
            }

            if (startX >= (13 * dx)) {
                startX = dx;
                startY = startY + dy;
            } else {
                startX = startX + 2 * dx;
            }
        }

        canvas.restore();
    }

    /**
     * 画被点击的那一天的状态
     * 画一矩形
     *
     * @param canvas
     */
    private void drawClickDay(Canvas canvas) {
        canvas.save();
        int left = (currentColumnNum - 1) * columnWidth + columnWidth / 6;
        int top = (currentRowNum - 1) * rowHeight + rowHeight / 6;
        int right = currentColumnNum * columnWidth - columnWidth / 6;
        int bottom = currentRowNum * rowHeight - rowHeight / 6;

        Rect rect = new Rect(left, top, right, bottom);

        paint.setColor(DEFAULT_CLICK_DAY_COLOR);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(rect, paint);

        canvas.restore();
    }

    /**
     * 画今天的状态
     *
     * @param canvas
     */
    private void drawNowDay(Canvas canvas) {
        canvas.save();

        int row;
        int column;

        int first = weekNumHash.get(firstDayWeek);

        if (nowDay <= (7 - first + 1)) {
            row = 1;
            column = first + (nowDay - 1);

        } else {
            row = (nowDay - (7 - first + 1)) / 7 + 2;
            column = (nowDay - (7 - first + 1)) % 7;
        }


        int left = (column - 1) * columnWidth + columnWidth / 6;
        int top = rowHeight / 6;
        int right = column * columnWidth - columnWidth / 6;
        int bottom = row * rowHeight - rowHeight / 6;

        Rect rect = new Rect(left, top, right, bottom);

        paint.setColor(nowDayColor);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(rect, paint);


        canvas.restore();
    }

    /**
     * 判断这一天是不是特殊的一天
     *
     * @param day
     * @return
     */
    private boolean isSpecialDay(int day) {
        for (int i = 0; i < specialDays.size(); i++) {
            int d = specialDays.get(i);
            if (d == day) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                float upX = event.getX();
                float upY = event.getY();
                if (Math.abs(upX - downX) < 10 && Math.abs(upY - downY) < 10) {
//                    performClick();
                    doClickLisAction((int) (upX + downX) / 2, (int) (upY + downY) / 2);
                }
                break;
            default:
                break;
        }

        return true;

    }

    /**
     * 日期的点击事件
     *
     * @param x
     * @param y
     */
    private void doClickLisAction(int x, int y) {

        //如果点击的位置在分界线上,就停止点击事件
        if (x % columnWidth == 0 || y % rowHeight == 0) {
            return;
        }

        //几行几列
        currentRowNum = y / rowHeight + 1;
        currentColumnNum = x / columnWidth + 1;

        int first = weekNumHash.get(firstDayWeek);
        int last = (currentMonthDayCount - (7 - first + 1)) % 7;


        //如果没有点击在日期上,就不需要重绘了
        if ((currentRowNum == 1 && currentColumnNum < first) || (currentRowNum == rowCount && currentColumnNum > last)) {
            return;
        }
        postInvalidate();
        onClickDayListener.onClickDay("2016-02-03");
    }


    public void lastMonthListener() {

    }


}
